package dao

import (
	"go_my_framework/app/core/db"
	"go_my_framework/app/model"
	"time"
)

type RoleInDao interface {
	GetList(int, int, string) ([]model.Role, int64, error)
	Create(string, string, int8) error
	Update(int, string, string, int8) error
	Find(id int) (data model.Role, err error)
	Del(id int) error
}

func NewRoleDaoTmpl() RoleInDao {
	return new(RoleDaoImpl)
}

type RoleDaoImpl struct {
}

func (r *RoleDaoImpl) GetList(page int, limit int, name string) (data []model.Role, count int64, err error) {
	obj := db.Instance().Model(model.Role{})
	if name != "" {
		obj.Where("name like ?", "%"+name+"%")
	}
	obj = obj.Count(&count)
	err = obj.Limit(limit).Offset((page - 1) * limit).Find(&data).Error
	return data, count, err
}

func (r *RoleDaoImpl) Find(id int) (data model.Role, err error) {
	err = db.Instance().Model(model.Role{}).Where("id = ?", id).Find(&data).Error
	return data, err
}

func (r *RoleDaoImpl) Create(name string, desc string, super int8) error {
	dateTime := time.Now().Format("2006-01-02 15:04:05")
	data := model.Role{}
	data.Name = name
	data.Desc = desc
	data.Super = super
	data.CreatedAt = dateTime
	data.UpdatedAt = dateTime
	err := db.Instance().Model(model.Role{}).Create(&data).Error
	return err
}

func (r *RoleDaoImpl) Update(id int, name string, desc string, super int8) error {
	data := make(map[string]interface{})
	data["name"] = name
	data["desc"] = desc
	data["super"] = super
	return db.Instance().Model(model.Role{}).Where("id = ?", id).Updates(data).Error
}

func (r *RoleDaoImpl) Del(id int) error {
	return db.Instance().Where("id = ?", id).Delete(model.Role{}).Error
}
